# -*- coding:utf-8 -*-
"""
@author: fsksf

@since: 2022/2/24 20:34
"""
from vcat.core.event import Event, EventType
from vcat.core.constant import (
    HandlerLevel,
)

from vcat.core.obj import (
    OrderRequest,
    ContractData,
)
from vcat.core.event_bus import (
    EventBus,
    event_bus_right,
    AsOrderReqChecker
)


class GuardRight:

    def __init__(self, main_engine):
        self._main_engine = main_engine
        self.event_bus_right: EventBus = event_bus_right

    @AsOrderReqChecker(level=HandlerLevel.FIRST)
    def check_order_cid(self, event: Event):
        req: OrderRequest = event.data
        contract: ContractData = self._main_engine.get_contract(req.cid)
        if contract is None:
            req.passed = False
            req.error_info = f'标的 <{req.cid}> 不存在'
            return False
        else:
            req.code = contract.code
            req.exchange = contract.exchange
            req.broker_name = contract.broker_name
            req.contract_type = contract.contract_type
            return True

    def check_send_order(self, req: OrderRequest):
        """
        验证并发送订单，
        验证期间允许修改订单数据
        :param req:
        :return:
        """
        for handler in self.event_bus_right.get_order_checker():
            if not handler.handler(req):
                self.event_bus_right.put(Event(event_type=EventType.LOG, data=f'订单验证未通过 <{handler.handler}> {req.error_info}'))
                return None
        return self.send_order(req)

    def send_order(self, req: OrderRequest):
        raise NotImplementedError
